package com.example.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.auth.config.exception.GlobalExcetion;
import com.example.auth.domain.DataNodeConfig;
import com.example.auth.domain.User;
import com.example.auth.domain.vo.UserVo;
import com.example.auth.service.DataNodeConfigService;
import com.example.auth.service.UserService;
import com.example.auth.mapper.UserMapper;
import com.example.auth.util.TotalBasedRoundRobinAllocator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author CETC
* @description 针对表【user】的数据库操作Service实现
* @createDate 2025-09-21 15:13:06
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private DataNodeConfigService dataNodeConfigService;

    @Override
    public User findByUsername(String username) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, username);
        return super.getOne(lambdaQueryWrapper);
    }

    @Override
    public User registerUser(User user) throws GlobalExcetion {
        User oldUser = findByUsername(user.getUsername());
        if(oldUser != null){
            throw new GlobalExcetion(101,"用户已存在");
        }
        Integer total=findUserTotalNum();
        List<DataNodeConfig> list=dataNodeConfigService.list();
        TotalBasedRoundRobinAllocator base=new TotalBasedRoundRobinAllocator(list);
        DataNodeConfig nodeConfig=base.allocateNodeByTotal(total);
        user.setNodeId(nodeConfig.getId());
        this.save(user);
        return user;
    }

    @Override
    public Integer findUserTotalNum() {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        return this.count(lambdaQueryWrapper);
    }

    @Override
    public DataNodeConfig findDataNodeByUserName(String userName) {
        User user = findByUsername(userName);
        if(user == null || user.getNodeId() == null){
            return null;
        }
        return dataNodeConfigService.getById(user.getNodeId());
    }
}




